package org.barad.architecture.analyzer.widgets;

import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.EventObject;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellEditor;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;

import org.apache.log4j.Logger;
import org.barad.architecture.analyzer.model.impl.Specification;

public class CustomTreeCellEditor extends DefaultTreeCellEditor {
	private Logger log = Logger.getLogger(getClass());
		
	public CustomTreeCellEditor(JTree tree, DefaultTreeCellRenderer renderer) {
		super(tree, renderer);
	}

	@Override
	public boolean isCellEditable(EventObject event) {
		boolean editable = tree.isEditable();
		Point mousePssition = tree.getMousePosition();
		if (mousePssition != null) {
			int x = (int)mousePssition.getX();
			int y = (int)mousePssition.getY();
			TreePath pathToSelect = tree.getPathForLocation(x, y);
			if (pathToSelect != null && editable) {	
				DefaultMutableTreeNode node = (DefaultMutableTreeNode)pathToSelect.getLastPathComponent();		
				Class<?> userObjectClass = node.getUserObject().getClass();
				log.debug("User object class: " + userObjectClass.toString());
				if (node.getUserObject() instanceof Specification) {
					Specification p = (Specification)node.getUserObject();
					log.debug("User object (property) value: " + p.getName());
				}
				if (!node.isLeaf() || !(userObjectClass.isAssignableFrom(Specification.class))) {
					editable = false;
				}
			}
		}
		return editable;
	}

	@Override
	public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, 
			boolean expanded, boolean leaf, int row) {
		//we edit only cells that contain Specification object
		CustomMutableTreeNode node = (CustomMutableTreeNode)value;
		CustomJTextField text = new CustomJTextField(tree, node);
		text.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				CustomJTextField text = (CustomJTextField)e.getSource();
				CustomMutableTreeNode node = (CustomMutableTreeNode)text.getNode();
				text.getTree().clearSelection();
				Specification specification = (Specification)node.getUserObject();
				String value = text.getText();
				specification.setName(value);
				node.setName(value);
			}
		});
		return text;
	}
}
